package org.zcl.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.zcl.service.BaseService;
import org.zcl.utils.RedisHelper;

import java.util.Collections;
import java.util.concurrent.Executor;

/**
 * .
 *
 * @author zhuchenglin
 * @since 2024/4/22 16:31
 */
@Service
@Slf4j
public class BaseServiceImpl implements BaseService {

    @Autowired
    private RedisHelper redisHelper;

    private final Executor asyncCouponExecutor;

    public BaseServiceImpl(@Qualifier("asyncCoupon") Executor asyncCouponExecutor) {
        this.asyncCouponExecutor = asyncCouponExecutor;
    }

    @Override
    public Long incr(int times) {
        for (int i = 0; i < times; i++) {
            asyncCouponExecutor.execute(() -> {
                process(times);
            });
        }

        return 0L;
    }

    private void process(int times) {
        String key = "KEY_" + times;
        Long count = redisHelper.incrNum(key);
        log.info("count:{},{}", count, Thread.currentThread().getName());
        if (count == times) {
            log.info("end");
            redisHelper.deleteKey(key);
        }
    }

    private void process2(int times) {
        String key = "KEY_" + times;
        String luaScript =
                "local count = redis.call('INCR', KEYS[1]) " +
                        "if count == tonumber(ARGV[1]) then " +
                        "   redis.call('DEL', KEYS[1]) " +
                        "   return 1 " +
                        "else " +
                        "   return 0 " +
                        "end";
        Long isLast = redisHelper.executeScript(luaScript,
                Collections.singletonList(key),
                Collections.singletonList(String.valueOf(times))
        );

        log.info("count: {}, isLast: {}", redisHelper.getNum(key), isLast);
        if (isLast == 1) {
            log.info("最后一个操作，Key已删除");

            redisHelper.deleteKey(key);
        }
    }
}
